//
//  FirstViewController.m
//  SITABLE
//
//  Created by songjun on 16/9/9.
//  Copyright © 2016年 Sita. All rights reserved.
//

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setValue:@"no" forKey:@"LinBoardIsLogOff"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    self.title = NSLocalizedStringFromTable(@"PallaBike", @"InfoPlist", nil);
    baseMapview.delegate = self;
    locationManager = [[AMapLocationManager alloc]init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy =kCLLocationAccuracyBest;

    [locationManager startUpdatingLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toConnectBleNoty) name:@"toConnectBleNoty" object:nil];
    
//    //初始化蓝牙
//    baby = [BabyBluetooth shareBabyBluetooth];
//    
//    //扫描并连接设备
//    [self babyDelegate];
//    baby.scanForPeripherals().connectToPeripherals().begin();
    
    refreshBodaoLocTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(requestBikeLocNow) userInfo:nil repeats:YES];
}


-(void)requestBikeLocNow
{
    NSString *bodaoUrl = [NSString stringWithFormat:@"%@%@%@",linboardBodaoGetToken,linboardBodaoid,@"&password=123456&grant_type=password&scope=single"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer setTimeoutInterval:10.0f];
    
    [manager POST:bodaoUrl parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       // NSLog(@"*****:%@",responseObject);
            [[NSUserDefaults standardUserDefaults] setValue:[responseObject valueForKey:@"access_token"] forKey:@"linboardBodaoAccessToken"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self requestBikeLocTure];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //NSLog(@"%@",error);
    }];
}

-(void)requestBikeLocTure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setTimeoutInterval:10.0f];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@ %@",@"bearer",[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardBodaoAccessToken"]] forHTTPHeaderField:@"Authorization"];
    
    NSString *mUrl = [NSString stringWithFormat:@"%@%@",linboardBodaoGetLoc,linboardBodaoid];
    //NSLog(@"****:%@",mUrl);
    [manager GET:mUrl parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         BodaoLoc *bettryInfo = [BodaoLoc mj_objectWithKeyValues:responseObject];
        
        CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:[bettryInfo.lat doubleValue] longitude:[bettryInfo.lng doubleValue]];
        CLLocation *converterStartLoc = [startLocation locationMarsFromEarth];
        
        CLLocationCoordinate2D coordBike = converterStartLoc.coordinate;
        
        if (!mySelfAnnotation) {
            mySelfAnnotation = [[MAPointAnnotation alloc] init];
            mySelfAnnotation.title = @"我的位置";
            [baseMapview addAnnotation:mySelfAnnotation];
            mySelfAnnotation.coordinate = coordBike;
            [baseMapview setZoomLevel:15.6];
            [baseMapview setCenterCoordinate:coordBike animated:YES];
        }else{
            mySelfAnnotation.coordinate = coordBike;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ;
        //NSLog(@"***:%@",error);
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    //获取当前连接的外设
    [super viewWillAppear:YES];
    baby = [BabyBluetooth shareBabyBluetooth];
    myPeripheral = [baby findConnectedPeripheral:[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardPName"]];
    
    if (myPeripheral) {
       baby.having(myPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
        .readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    }
    
    //设置读取characteristics的委托
    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        //NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
        if ([characteristics.UUID.description isEqualToString:linboardPublicCharacteristic]) {
            // NSLog(@"sdfasdfasdfasdfds");
            //myPeripheral = peripheral;
            myCharactertistic = characteristics;
        }
    }];
    
    [refreshBodaoLocTimer resumeTimer];
    
}


-(void)toConnectBleNoty
{
//    //初始化蓝牙
//    baby = [BabyBluetooth shareBabyBluetooth];
//    //扫描并连接设备
//    [self babyDelegate];
//    baby.scanForPeripherals().connectToPeripherals().begin();
    
    baby = [BabyBluetooth shareBabyBluetooth];
        myPeripheral = [baby findConnectedPeripheral:[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardPName"]];
        if (myPeripheral) {
            baby.having(myPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
            .readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
        }
    
        //设置读取characteristics的委托
        [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
            //NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
            if ([characteristics.UUID.description isEqualToString:linboardPublicCharacteristic]) {
                // NSLog(@"sdfasdfasdfasdfds");
                //myPeripheral = peripheral;
                myCharactertistic = characteristics;
            }
        }];
}

-(void)scanBtnAction:(UIButton *)btn
{
    ScanBleViewController *peripheralVc =   [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"scanBleVc"];
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
    temporaryBarButtonItem.title = @"";
    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;

    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:peripheralVc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1002) {
        if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:@"prefs:root=Bluetooth"];
          if ([[UIApplication sharedApplication] canOpenURL:url]) {
              [[UIApplication sharedApplication] openURL:url];
          }
        }
    }
}

-(void)babyDelegate
{
    //peripheralManagerDidUpdateState
    [baby peripheralModelBlockOnPeripheralManagerDidUpdateState:^(CBPeripheralManager *peripheral) {
        if (peripheral.state==CBManagerStatePoweredOn) {
            baby = [BabyBluetooth shareBabyBluetooth];
            //扫描并连接设备
            [self babyDelegate];
            baby.scanForPeripherals().connectToPeripherals().begin();
        }
        
        if (peripheral.state == CBManagerStateUnauthorized) {
            UIAlertView *alertToOpenBle = [[UIAlertView alloc] initWithTitle:@"需要开启蓝牙" message:@"请在设置中打开蓝牙" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertToOpenBle.tag =1002;
            [alertToOpenBle show];
        }
    }];

    __block FirstViewController *myself = self;
    
    [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        //NSLog(@"搜索到了设备:%@",peripheral.name);
        if ([peripheral.name isEqualToString:@"SITA01000002"]) {
            myPeripheral = peripheral;
            if (myPeripheral!=nil) {
                //读取
                myself->baby.having(myself->myPeripheral).connectToPeripherals().discoverServices().discoverCharacteristics()
                .readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
            }
        }
    }];
    
    //断开自动重连
    [baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
       // NSLog(@"设备：%@--断开连接",peripheral.name);
        if (myPeripheral!=nil&&myCharactertistic!=nil) {
             [myself->baby AutoReconnect:myself->myPeripheral];
        }
    }];
    

    //设置发现设service的Characteristics的委托
    [baby setBlockOnDiscoverCharacteristics:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
       // NSLog(@"===service name:%@",service.UUID);
    }];
    
    //设置读取characteristics的委托
    [baby setBlockOnReadValueForCharacteristic:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        //NSLog(@"characteristic name:%@ value is:%@",characteristics.UUID,characteristics.value);
        if ([characteristics.UUID.description isEqualToString:@"FFE1"]) {
            //NSLog(@"****:%@,%@",peripheral,characteristics);
            myPeripheral = peripheral;
            myCharactertistic = characteristics;
            if (!myself->getBlePwdTimer) {
                getBlePwdTimer= [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getBlePwdTimer) userInfo:nil repeats:YES];
            }else{
                 [myself->getBlePwdTimer resumeTimer];
            }
            
            //注册特征值监听回调
            [myself->baby notify:peripheral characteristic:characteristics block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
                //NSLog(@"%@",characteristics.value);
                NSString *result  = [myself convertDataToHexStr:characteristics.value];
                //NSLog(@"回调:::%@",result);
                if ([result hasPrefix:linboardPWDResponse]){
                    //保存密码:
                    [myself->getBlePwdTimer pauseTimer];
                    //linboardBlePassword
                    NSString *subString=[result substringFromIndex:linboardPWDResponse.length];
                    //NSLog(@"第一次截取:%@",subString);
                    NSString *sub1S = [subString substringToIndex:subString.length-4];
                    //NSLog(@"真正的密码:%@",sub1S);
                    [[NSUserDefaults standardUserDefaults] setValue:sub1S forKey:@"linboardBlePassword"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }];
        }
    }];
}

-(NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}

-(void)getBlePwdTimer
{
    NSString *linboardGetBlePwd =linboardSearchPwdString;
    NSData *transData = [linboardGetBlePwd hexToBytes];
    if (myPeripheral!=nil&&myCharactertistic!=nil) {
        [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
    }
}



-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
//    CAGradientLayer *layer1 = [[CAGradientLayer alloc] init];
//    layer1.colors = @[(__bridge id)UIColorHexRGBA(linBoardBGStartColor, 1.0).CGColor, (__bridge id)UIColorHexRGBA(linBoardBGEndColor, 1.0).CGColor];
//    layer1.startPoint = CGPointMake(0, 0);
//    layer1.endPoint = CGPointMake(0, 1);
//    layer1.frame = botomeView.bounds;
//    [botomeView.layer addSublayer:layer1];
//    [botomeView.layer insertSublayer:layer1 atIndex:0];
    
}



- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
//    if (!mySelfAnnotation) {
//        mySelfAnnotation = [[MAPointAnnotation alloc] init];
//        mySelfAnnotation.title = @"我的位置";
//        [baseMapview addAnnotation:mySelfAnnotation];
//        mySelfAnnotation.coordinate = location.coordinate;
//        [baseMapview setZoomLevel:15.6];
//        [baseMapview setCenterCoordinate:location.coordinate animated:YES];
//    }else{
//        mySelfAnnotation.coordinate = location.coordinate;
//    }
}


-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [refreshBodaoLocTimer pauseTimer];
    
    
}

-(void)deletehudNow
{
    MBProgressHUD *hud = [self.view viewWithTag:1044];
    [hud removeFromSuperview];
}

#pragma mark ------viewForAnnotation------

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
     [baseMapview deselectAnnotation:view.annotation animated:YES];
//    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithFrame:self.view.frame];
//    hud.mode = MBProgressHUDModeText;
//    hud.tag = 1044;
//    [self.view addSubview:hud];
//    hud.labelText = @"正在连接......";
//    [hud show:YES];
//    
//    
//    baby = [BabyBluetooth shareBabyBluetooth];
//    //扫描并连接设备
//    [self babyDelegate];
//    baby.scanForPeripherals().connectToPeripherals().begin();
//    
//    [self performSelector:@selector(deletehudNow) withObject:self afterDelay:5.0];
//
//    FindBikeViewController *peripheralVc =   [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"findBikeVc"];
//    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
//    temporaryBarButtonItem.title = @"";
//    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
//    
//    self.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:peripheralVc animated:YES];
//    self.hidesBottomBarWhenPushed = NO;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    static NSString *reuseIndetifier = @"userCurrentLocationAnnotation";
    MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
    annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
    if ([[annotation title] isEqualToString:@"我的位置"])
    {
        annotationView.frame = CGRectMake(0, 0, 53, 53);
        //annotationView.image = [UIImage imageNamed:@"locationMyself"];
        UIImageView *testIv = [[UIImageView alloc] initWithFrame:CGRectMake(55/2-25/2, 55/2-25/2, 25, 25)];
        testIv.image =[UIImage imageNamed:@"carLocation"];
        [annotationView addSubview:testIv];
        
        annotationView.canShowCallout = NO;
        // 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
    }
    return annotationView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)enginPowerBtnAciton:(UIButton *)sender {
    
    NSString *blePwd =[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardBlePassword"];
    
    if (sender.selected) {
        sender.selected = NO;
        [sender setImage:[UIImage imageNamed:@"startEnIv"] forState:UIControlStateNormal];
        if (blePwd.length!=0) {
            NSString *linboardStartEngineS = [NSString stringWithFormat:@"%@%@%@",linboardStartEngineHead,blePwd,linboardStartEngineTail];
            NSData *transData = [linboardStartEngineS hexToBytes];
            if (myPeripheral!=nil&&myCharactertistic!=nil) {
                [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
            }
        }
        
        
    }else{
        sender.selected = YES;
        //关机
        [sender setImage:[UIImage imageNamed:@"endEngine"] forState:UIControlStateNormal];
        if (blePwd.length!=0) {
            NSString *linboardStartEngineS = [NSString stringWithFormat:@"%@%@%@",linboardStopEngineHead,blePwd,linboardStopEngineTail];
            NSData *transData = [linboardStartEngineS hexToBytes];
            if (myPeripheral!=nil&&myCharactertistic!=nil) {
                [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
            }
        }

    }

}

- (IBAction)lockBikeBtnAciton:(UIButton *)sender
{
    NSString *blePwd =[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardBlePassword"];
    
    if (sender.selected) {
        sender.selected = NO;
        [sender setImage:[UIImage imageNamed:@"unlockIv"] forState:UIControlStateNormal];
        if (blePwd.length!=0) {
            NSString *linboardDefenceS =[NSString stringWithFormat:@"%@%@%@",linboardDefenceHead,blePwd,linboardDefenceTail];
            NSData *transData = [linboardDefenceS hexToBytes];
            if (myPeripheral!=nil&&myCharactertistic!=nil) {
                [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
            }
        }
    }else{
        sender.selected = YES;
        [sender setImage:[UIImage imageNamed:@"lockIv"] forState:UIControlStateNormal];
        if (blePwd.length!=0) {
            NSString *linboardDefenceS =[NSString stringWithFormat:@"%@%@%@",linboardUndefenceHead,blePwd,linboardUndefenceTail];
            NSData *transData = [linboardDefenceS hexToBytes];
            if (myPeripheral!=nil&&myCharactertistic!=nil) {
                [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
            }
        }

    }
}

- (IBAction)findBikeBtnAction:(UIButton *)sender
{
    NSString *blePwd =[[NSUserDefaults standardUserDefaults] valueForKey:@"linboardBlePassword"];
    if (blePwd.length!=0) {
        NSString *linboardSearchBikeS =[NSString stringWithFormat:@"%@%@%@",linboardSearchBikeHead,blePwd,linboardSearchBikeTail];
        NSData *transData = [linboardSearchBikeS hexToBytes];
        
        if (myPeripheral!=nil&&myCharactertistic!=nil) {
            [myPeripheral writeValue:transData forCharacteristic:myCharactertistic type:CBCharacteristicWriteWithoutResponse];
        }
    }
}


- (IBAction)locateBtnAction:(UIButton *)sender
{
    
}


- (IBAction)locateAciton:(UIButton *)sender
{
    [baseMapview setCenterCoordinate:mySelfAnnotation.coordinate animated:YES];
}
@end
